import {
  Form
} from 'antd-mini/es/Form/form';
import {
  workOrdeDealOrder,
  getSubcategoryTypeList,
  workOderAudit,
  imageUpload
} from '/service/service'

Page({
  data: {
    id: null,
    data: null,

    faultCategory: '',
    faultCategoryList: ['前端', '后端', '外场巡检'],
    faultSubcategory: '',
    faultSubcategoryList: [],
    isAccident: '',
    isAccidentOptions: [{
        text: '是',
        value: '是'
      },
      {
        text: '否',
        value: '否'
      },
    ],
    attachments: []
  },
  onLoad(option) {
    const id = option.id
    this.setData({
      id
    })
    this.form = new Form({
      initialValues: {},
      rules: {
        faultCategory: [{
          required: true,
          message: '请选择故障大类',
        }],
        faultSubcategory: [{
          required: true,
          message: '请选择故障小类',
        }],
        isAccident: [{
          required: true,
          message: '请选择是否事故',
        }],
        fixResult: [{
          required: true,
          message: '请输入修复结果',
        }],
        attachments: [{
          required: true,
          message: '请上传故障图片',
        }],
      },
    })
    this.getInfo(id)
    this.getSubcategoryTypeList()
  },
  getSubcategoryTypeList() {
    getSubcategoryTypeList().then(res => {
      const {
        rows
      } = res
      if (res && rows && rows.length > 0) {
        const faultSubcategoryList = []
        rows.forEach(item => {
          faultSubcategoryList.push(item.typeName)
        })
        this.setData({
          faultSubcategoryList
        })
      }
    })
  },
  async getInfo(id) {
    try {
      const data = await workOderAudit(id)
      this.setData({
        data
      })

      this.setFormValues(data)
    } catch (error) {
      console.error('获取数据失败:', error)
    }
  },
  setFormValues(data) {
    if (!this.form) return
    const formValues = {
      ...data
    }
    this.form.setFieldsValue(formValues)
  },

  handleRef(ref) {
    this.form.addItem(ref)
  },
  async submit() {
    try {
      const values = await this.form.submit()
      const {
        id,
        attachments
      } = this.data
      const params = {
        ...values,
        id,
        attachments
      }

      const res = await workOrdeDealOrder(params)
      // my.navigateBack();
      if (res && res.code === 200) {
        this.showtoast(res.msg)
        my.navigateBack()
      } else {
        this.showtoast('提交失败，请检查', 'fail')
      }
    } catch (e) {
      console.log(e)
      this.showtoast(e, 'fail')
    }
  },
  auditResultChange(e) {
    this.setData({
      auditResult: e
    })
  },
  cancel() {
    my.navigateBack();
  },
  imageRemove(e) {
    console.log(e)
    const {
      path,
      url
    } = e
    const originPath = path ? path : url
    const fileNameFromPath = originPath.split('/').pop()
    const list = this.data.attachments
    const filteredList = list.filter(item => item.fileName !== fileNameFromPath)
    this.setData({
      attachments: filteredList
    })
  },
  imageBeforeUpload(localFileList) {
    const {
      attachments
    } = this.data
    if (attachments.length === 0) {
      return new Promise(res => {
        res(localFileList[0])
      })
    } else {
      const {
        path
      } = localFileList[0]
      const waitingUploadPathName = path.split('/').pop()
      if (waitingUploadPathName === attachments[0].fileName) {
        console.log('已存在')
        return false
      } else {
        return new Promise(res => {
          res(localFileList[0])
        })
      }

    }
  },
  async onUpload(localFile) {
    if (!localFile || !localFile.path) {
      console.error('上传失败：未获取到有效的图片临时路径');
      throw new Error('上传失败：未获取到有效的图片临时路径');
    }

    const tempFilePath = localFile.path;
    const res = await imageUpload(tempFilePath);
    if (!res) {
      console.error('上传失败：接口未返回有效的图片URL');
      throw new Error('上传失败：接口未返回有效的图片URL');
    }
    const attachments = this.data.attachments
    attachments.push(res)
    this.setData({
      attachments
    })
    return tempFilePath;
  },
  imagePreview(file) {
    const {
      url
    } = file
    if (!url) return
    this.previewSingleImage(url)
  },
  previewSingleImage(url) {
    dd.previewImage({
      urls: [url],
      current: url,
      success: () => {
        console.log('图片预览成功');
      },
      fail: (err) => {
        console.error('图片预览失败', err);
        this.showtoast('预览失败，请检查', 'fail')
      }
    });
  },
  showtoast(content = '操作成功', type = 'success', duration = 2000) {
    my.showToast({
      content,
      type,
      duration
    })
  }
});